<?php

namespace yunj\validate;

use yunj\Validate;

class YunjForm extends Validate {

    protected $rule = [
        'builder_id' => 'require',
        'builder_async_type' => 'require|in:load,submit',
    ];

    protected $message = [
        'builder_id.require' => '访问错误',
        'builder_async_type.require' => '[builder_async_type]参数缺失',
        'builder_async_type.in' => '[builder_async_type]参数错误',
    ];

    protected $scene = [
        'async_request' => ['builder_id', 'builder_async_type'],
    ];

    protected function handleData(array $raw_data, $scene): array {
        $data = $raw_data;
        if ($scene == 'async_request') {
            switch ($raw_data['builder_async_type']) {
                case 'load':
                    $data = $this->handleDataByLoad($raw_data);
                    break;
                case 'submit':
                    $data = $this->handleDataBySubmit($raw_data);
                    break;
            }
        }
        return $data;
    }

    private function handleDataByLoad($raw_data) {
        $data = $raw_data;
        return $data;
    }

    private function handleDataBySubmit($raw_data) {
        $data = $raw_data;
        if (!isset($raw_data['data'])) throw_error_json('[data]参数缺失');
        $data['data'] = json_decode($raw_data['data'], true);
        if (!isset($raw_data['tab_data'])) throw_error_json('[tab_data]参数缺失');
        $data['tab_data'] = json_decode($raw_data['tab_data'], true);
        return $data;
    }
}